package com.mrd.frame.quartz;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import com.mrd.frame.config.quartz.ScheduleJob;

/**
 * 初始化调度器，先手动初始化，添加要执行的定时器，后面改造成读取数据库
 * @author han
 */
@Component
public class TaskInitBean implements InitializingBean {

	@Autowired
	SchedulerFactoryBean schedulerFactoryBean;

	/**
	 * spring 初始化方法，把要调度的定时器在这里初始化
	 * @auhtor han
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		ScheduleJob job = new ScheduleJob();
		job.setBeanClass("com.mrd.frame.quartz.CleanImgTask");
		job.setCronExpression("0 0 */2 * * ? *");
		job.setDescription("清理二维码图片");
		job.setIsConcurrent(job.CONCURRENT_NOT);
		job.setJobGroup("testGroup");
		job.setJobName("cleanTask");
		job.setJobStatus("1");
		job.setJobId(new Long(1));
		job.setSpringId("");
		job.setMethodName("execute");
		addJob(job);
		
		ScheduleJob job2 = new ScheduleJob();
		job2.setBeanClass("com.mrd.frame.quartz.ResendMessageTask");
		job2.setCronExpression("0 0/1 * * * ?");
		job2.setDescription("消息重发");
		job2.setIsConcurrent(job.CONCURRENT_NOT);
		job2.setJobGroup("testGroup");
		job2.setJobName("resendMessage");
		job2.setJobStatus("1");
		job2.setJobId(new Long(2));
		job2.setSpringId("");
		job2.setMethodName("execute");
		addJob(job2);
	}

	/**
	 * 添加任务
	 * @author han
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public void addJob(ScheduleJob job) throws Exception {
		if (job == null
				|| !ScheduleJob.STATUS_RUNNING.equals(job.getJobStatus())) {
			return;
		}

		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(),
				job.getJobGroup());
		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		Class clazz = (Class.forName(job.getBeanClass()).newInstance())
				.getClass();
		JobDetail jobDetail = JobBuilder.newJob(clazz)
				.withIdentity(job.getJobName(), job.getJobGroup()).build();
		jobDetail.getJobDataMap().put("scheduleJob", job);
		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
				.cronSchedule(job.getCronExpression());
		trigger = TriggerBuilder.newTrigger()
				.withIdentity(job.getJobName(), job.getJobGroup())
				.withSchedule(scheduleBuilder).build();
		scheduler.scheduleJob(jobDetail, trigger);
	}

}
